<?php
/**
 * ResMania
 * More Information contact: info@resmania.com
 *
 * @package Joomla User to ResMania User Connector
 * @version 0.5
 * @author webformatique
 * @copyright (C) 2010- webformatique
 * @license GNU/GPLv3 http://www.gnu.org/copyleft/gpl.html
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

class RM_Joomla_User implements RM_User_CMS_Interface {
    /**     
     * @var JUser
     */
    private $_user;

    /**
     * Constructor
     * @param JUser $user 
     */
    public function  __construct(JUser $user) {
        $this->_user = $user;
    }

    /**
     * This method indicates is CMS user a guest or already registered CMS user
     * @return bool
     */
    public function isGuest(){
        return $this->_user->get('guest');
    }

    /**
     * Tries to find a Resmania user that linked to CMS user, if not returns null
     * @return RM_User_Row|null
     */
    public function findResmaniaUser(){
        $model = new RM_Users();
        $resmaniaUser = $model->getByField('cms_id', $this->_user->get('id'))->current();
        return $resmaniaUser;
    }

    /**
     * Convert CMS user objcet into RM_User_Row object (without saving it into database)
     * @return RM_User_Row
     */
    public function convertToResmaniaUser(){
        $model = new RM_Users();
        $user = $model->createRow();

        $name = explode(" ",$this->_user->get('name')); // split up to an array

        $first_name = $name[0];
        $last_name =  $name[1];

        if (isset($name[2])) $last_name.= " ".$name[2]; // handle double barrelled
        if (isset($name[3])) $last_name.= " ".$name[3]; // handle double barrelled

        $user->cms_id = $this->_user->get('id');
        $user->first_name = $first_name;
        $user->last_name = $last_name;
        $user->username = $this->_user->get('username');
        $user->email = $this->_user->get('email');

        return $user;
    }

    /**
     * Return internal object JUser this method should be called only from Joomla connector classes
     *
     * @return JUser
     */
    public function getUser(){
        return $this->_user;
    }
}